﻿using HCQ2_Common;
using HCQ2_Common.SQL;
using HCQ2_IDAL;
using HCQ2_Model.ParamsModel;
using HCQ2_Model.ViewModel;
using HCQ2_Model.ViewModel.VR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HCQ2_DAL_MSSQL
{
    /// <summary>
    /// 订单相关    
    /// </summary>
    public partial class T_VROrderDAL: IT_VROrderDAL
    {
        /// <summary>
        /// 获取一个订单编号
        /// </summary>
        /// <returns></returns>
        public string GetOrderCode()
        {
            string sql = "select REPLACE(NEWID(),'-','')";
            Object o = SqlHelper.ExecuteScalar(sql);
            if (o == null)
            {
                new Exception("生成订单编号为空");
            }
            return o.ToString();
        }
        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="orderListParams"></param>
        /// <returns></returns>
        public TableModel GetOrderList(OrderListParams orderListParams)
        {
            StringBuilder where = new StringBuilder(2);
            where.Append(string.Format("o.status={0}",orderListParams.statu));
            if (!string.IsNullOrEmpty(orderListParams.orderCode)) {
                where.Append(string.Format(" and order_code like '%{0}%'", orderListParams.orderCode));
            }
            if (orderListParams.userId != null) {
                where.Append(string.Format(" and o.user_id={0}",orderListParams.userId.Value));
            }

            string sql = string.Format(@"select o.order_code orderCode,pay_money money,pay_pramoney pramoney,create_time cTime,handle_time hTime,u.user_name userName from T_VROrder o
            left join T_User u on o.user_id=u.user_id
            where {0}", where.ToString());

            List<OrderList> orderList = SqlHelper.ExecutePageList<OrderList>(orderListParams.page,orderListParams.rows,
                "cTime",sql,false
                );

            int count = SqlHelper.GetCount(sql);

            return new TableModel {
                rows = orderList,
                total = count
            };
        }

        /// <summary>
        /// 获取订单详细
        /// </summary>
        /// <param name="orderCode">订单编号</param>
        /// <returns></returns>
        public OrderDetailed GetOrderDetailed(string orderCode)
        {
            //订单详细
            string sql = string.Format("select order_code orderCode,pay_money money,pay_pramoney pramoney,create_time cTime from T_VROrder where order_code='{0}'", orderCode);

            OrderDetailed detailed = SqlHelper.ExecuteList<OrderDetailed>(sql)[0];

            //订单商品信息
            sql = string.Format("select file_name name,file_type type,(CASE WHEN file_size > 999 THEN CAST(CAST(file_size / 1024 AS DECIMAL(10, 2)) AS NVARCHAR(20)) + 'M' ELSE CAST(file_size AS NVARCHAR(20)) + 'KB' END) size,file_classify classify,file_money money from T_VROrderDetail where order_code='{0}'", orderCode);
            List<OrderCommodity> commodityList = SqlHelper.ExecuteList<OrderCommodity>(sql);
            detailed.commoditys = commodityList;

            return detailed;
        }
        /// <summary>
        ///  判断用户是否购买商品
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int GetShoppingFile(int fileId, int userId)
        {
            sb?.Clear();
            sb.AppendFormat("SELECT COUNT(0) as fileCount FROM T_VROrderDetail WHERE file_id={0} AND order_code IN(SELECT order_code FROM T_VROrder WHERE user_id={1} AND status IN(0,2));", fileId, userId);
            return Helper.ToInt(SqlHelper.ExecuteScalar(sb.ToString()));
        }
        //********************************************接口************************************************
        /// <summary>
        ///  判断当前文件是否是被用户购买
        /// </summary>
        /// <param name="user_id">用户id</param>
        /// <param name="file_id">文件id</param>
        /// <returns></returns>
        public int GetOrderResult(int user_id, int file_id)
        {
            sb?.Clear();
            sb.Append($@"SELECT COUNT(0) AS num FROM N_OrderCommodityInfo WHERE OrderCode  IN(SELECT OrderCode FROM dbo.N_Order WHERE OrderState in(2,4) AND OrderCreateUserId = {user_id}) AND file_id = {file_id};");
            return Helper.ToInt(SqlHelper.ExecuteScalar(sb.ToString()));
        }
        /// <summary>
        ///  更新商品购买订单状态为：成功
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="file_id"></param>
        /// <returns></returns>
        public void ModifyOrderStatus(int user_id, int file_id)
        {
            sb?.Clear();
            sb.Append($"UPDATE N_Order SET OrderState=4 WHERE OrderCode IN(SELECT OrderCode FROM N_OrderCommodityInfo WHERE file_id = {file_id}) AND OrderCreateUserId = {user_id};");
            SqlHelper.ExecuteScalar(sb.ToString());
        }
    }
}
